<template>
  <div class="widget-form-container">
    <!-- 
      :hide-required-asterisk="widgetForm.config.hideRequiredAsterisk"
      -->
    <ElForm
      label-suffix=":"
      class="mike_form"
      :label-position="widgetForm.config.labelPosition"
      :label-width="`${widgetForm.config.labelWidth}px`"
      :size="widgetForm.config.size"
    >
      <div class="button_area" v-if="widgetForm.button_area" :style="{ height: '15%' }">
        <div v-if="!widgetForm.button_area.length" class="form-empty-button"
          >从左侧拖拽添加按钮区（只识别按钮）</div
        >
        <draggable
          class="widget-form-button"
          item-key="id"
          ghostClass="ghost"
          handle=".drag-widget"
          :animation="200"
          :group="{ name: 'people' }"
          :list="widgetForm.button_area"
          :move="handleMoveAddStr"
          @add="handleMoveAdd($event, 'button_area')"
        >
          <template #item="{ element, index }">
            <transition-group
              name="fade"
              tag="div"
              class="mike_group"
              :style="{ width: element.width, height: element.height }"
            >
              <WidgetFormItem
                v-if="element.id"
                :key="element.id"
                :display="false"
                :element="element"
                :config="widgetForm.config"
                :selectWidget="widgetFormSelect"
                @click.stop="handleItemClick(element)"
                @copy="handleCopyClick(index, widgetForm.button_area, 'button_area')"
                @delete="handleDeleteClick(index, widgetForm.button_area, 'button_area')"
              />
            </transition-group>
          </template>
        </draggable>
      </div>
      <div
        class="display_area"
        v-if="widgetForm.display_area"
        :style="{
          height: widgetForm.button_area ? '75%' : '90%',
        }"
      >
        <div v-if="!widgetForm.display_area.length" class="form-empty">从左侧拖拽添加显示区</div>
        <draggable
          class="widget-form-display"
          item-key="id"
          ghostClass="ghost"
          handle=".drag-widget"
          :animation="200"
          :group="{ name: 'people' }"
          :list="widgetForm.display_area"
          :move="handleMoveAddStr"
          @add="handleMoveAdd($event, 'display_area')"
        >
          <template #item="{ element, index }">
            <transition-group
              name="fade"
              tag="div"
              class="mike_group"
              :style="{
                width: isTables ? '100%' : element.width == '' ? '100%' : element.width,
                height: element.height,
                marginTop: element.element_marginTop,
                marginBottom: element.element_marginBottom,
              }"
            >
              <WidgetFormItem
                v-if="element.id"
                :key="element.id"
                :display="false"
                :element="element"
                :config="widgetForm.config"
                :selectWidget="widgetFormSelect"
                :list="widgetForm.display_area"
                :allData="widgetForm"
                area="display_area"
                @click.stop="handleItemClick(element)"
                @copy="handleCopyClick(index, widgetForm.display_area, 'display_area')"
                @delete="handleDeleteClick(index, widgetForm.display_area, 'display_area')"
                @update:widgetFormSelectCore="updateWidgetFormSelectCore"
              />
            </transition-group>
          </template>
        </draggable>
      </div>
      <div class="hidden_area" v-if="widgetForm.hidden_area">
        <div v-if="!widgetForm.hidden_area.length" class="form-empty-hidden"
          >从各模块中拖拽添加隐藏区</div
        >
        <draggable
          class="widget-form-hidden"
          item-key="id"
          ghostClass="ghost"
          handle=".drag-widget"
          :animation="200"
          :group="{ name: 'people' }"
          :list="widgetForm.hidden_area"
          :move="handleMoveAddStr"
          @add="handleMoveAdd($event, 'hidden_area')"
        >
          <template #item="{ element, index }">
            <transition-group
              name="fade"
              tag="div"
              class="mike_group"
              :style="{
                width: '73.8px',
                height: '35px',
                border: ['tabs', 'grid', 'buttonArea', 'foldedPanel', 'divLayout'].includes(
                  element.element_control,
                )
                  ? '1px solid #e6a23c'
                  : '1px solid var(--el-color-primary)',
                outline: ['tabs', 'grid', 'buttonArea', 'foldedPanel', 'divLayout'].includes(
                  element.element_control,
                )
                  ? '1px solid #e6a23c'
                  : '1px solid var(--el-color-primary)',
                padding: '0',
              }"
            >
              <WidgetFormItem
                v-if="element.id"
                :key="element.id"
                :display="true"
                :element="element"
                :config="widgetForm.config"
                :selectWidget="widgetFormSelect"
                :list="widgetForm.hidden_area"
                :allData="widgetForm"
                area="hidden_area"
                @click.stop="handleItemClick(element)"
                @copy="handleCopyClick(index, widgetForm.hidden_area, 'hidden_area')"
                @delete="handleDeleteClick(index, widgetForm.hidden_area, 'hidden_area')"
                @update:widgetFormSelectCore="updateWidgetFormSelectCore"
              />
            </transition-group>
          </template>
        </draggable>
      </div>
      <div class="trash_area" v-if="widgetForm.trash_area">
        <div v-if="!widgetForm.trash_area.length" class="form-empty-trash">暂存回收站</div>
        <draggable
          class="widget-form-trash"
          item-key="id"
          :sort="false"
          ghostClass="ghost"
          handle=".drag-widget"
          :animation="200"
          :group="{ name: 'people' }"
          :list="widgetForm.trash_area"
          :move="handleMoveAddStr"
          @add="handleMoveAdd($event, 'trash_area')"
        >
          <template #item="{ element, index }">
            <transition-group
              name="fade"
              tag="div"
              class="mike_group"
              :style="{
                width: '73.8px',
                height: '35px',
                border: ['tabs', 'grid', 'buttonArea', 'foldedPanel', 'divLayout'].includes(
                  element.element_control,
                )
                  ? '1px solid #e6a23c'
                  : '1px solid var(--el-color-primary)',
                outline: ['tabs', 'grid', 'buttonArea', 'foldedPanel', 'divLayout'].includes(
                  element.element_control,
                )
                  ? '1px solid #e6a23c'
                  : '1px solid var(--el-color-primary)',
                padding: '0',
              }"
            >
              <WidgetFormItem
                v-if="element.id"
                :key="element.id"
                :display="true"
                :element="element"
                :config="widgetForm.config"
                :selectWidget="widgetFormSelect"
                :list="widgetForm.trash_area"
                :allData="widgetForm"
                :hidden="true"
                area="trash_area"
                @click.stop="handleItemClick(element)"
                @copy="handleCopyClick(index, widgetForm.trash_area, 'trash_area')"
                @delete="handleDeleteClick(index, widgetForm.trash_area, 'trash_area')"
                @update:widgetFormSelectCore="updateWidgetFormSelectCore"
              />
            </transition-group>
          </template>
        </draggable>
      </div>
    </ElForm>
  </div>
</template>

<script lang="ts" setup>
  document.body.ondrop = function (event) {
    event.preventDefault();
    event.stopPropagation();
  };
  // PropType
  import draggable from 'vuedraggable';
  import { v4 } from 'uuid';
  import WidgetFormItem from './WidgetFormItem.vue';
  // import { WidgetForm } from '@/types/element';
  const props = defineProps({
    widgetForm: {
      type: Object,
      required: true,
    },
    widgetFormSelect: {
      type: Object,
    },
    isTables: {
      type: Boolean,
      default: false,
    },
  });

  // watch(
  //   () => props,
  //   (value: any) => {
  //     console.log(value.widgetFormSelect);
  //     value.widgetForm.
  //   },
  //   {
  //     deep: true,
  //   },
  // );
  const emit = defineEmits<Emits>();
  interface Emits {
    (e: 'update:widgetFormSelect', value: Array<any> | any): void;
    (e: 'update:widgetForm', value?: any, list?: any, id?: string, copyData?: object): void;
  }
  const handleListInsert = (id: string, list: any[], obj: any) => {
    const newList: any[] = [];
    // 复制对象及子对象生成新的id
    const getElementId = (obj: any) => {
      const UUID = v4().replaceAll('-', '');
      obj.id = UUID;
      obj.element_code = `${obj.element_control}_${UUID}`;
      if (obj.columns) {
        obj.columns.forEach((col: any) => {
          col.list.forEach((it: any) => getElementId(it));
        });
      }

      if (obj.panes) {
        obj.panes.forEach((pane: any) => {
          pane.list.forEach((it: any) => getElementId(it));
        });
      }

      if (obj.panel) {
        obj.panel.forEach((panelItem: any) => {
          panelItem.list.forEach((it: any) => getElementId(it));
        });
      }
      // 优化div包裹布局内容复制
      if (obj.div_list) {
        obj.div_list.forEach((panelItem: any) => {
          panelItem.list.forEach((it: any) => getElementId(it));
        });
      }

      if (obj.list) {
        obj.list.forEach((it: any) => getElementId(it));
      }
    };
    [obj].forEach((item) => getElementId(item));
    if (list) {
      list.forEach((item) => {
        if (item.id === id) {
          newList.push(item);
          newList.push(obj);
        } else {
          if (item.columns) {
            item.columns = item.columns.map((col: any) => ({
              ...col,
              list: handleListInsert(id, col.list, obj),
            }));
          }
          if (item.panes) {
            item.panes = item.panes.map((col: any) => ({
              ...col,
              list: handleListInsert(id, col.list, obj),
            }));
          }
          if (item.panel) {
            item.panel = item.panel.map((col: any) => ({
              ...col,
              list: handleListInsert(id, col.list, obj),
            }));
          }
          if (item.div_list) {
            item.div_list = item.div_list.map((col: any) => ({
              ...col,
              list: handleListInsert(id, col.list, obj),
            }));
          }
          newList.push(item);
        }
      });
    }
    return newList;
  };

  const handleListDelete = (id: string, list: any[]) => {
    const newList: any[] = [];
    if (list) {
      list.forEach((item) => {
        if (item.id !== id) {
          newList.push(item);
        }
      });
    }
    return newList;
  };
  const updateWidgetFormSelectCore = (row: any) => {
    emit('update:widgetFormSelect', row);
  };

  const handleItemClick = (row: any) => {
    emit('update:widgetFormSelect', row);
  };
  const handleFunctionCopy = (list: any[], index: number) => {
    if (list[index].columns) {
      list[index].columns = list[index].columns.map((item) => {
        if (item.list.length) {
          item.list = item.list.map((it) => {
            return {
              ...it,
              id: v4().replaceAll('-', ''),
              element_code: `${it.element_control}_${v4().replaceAll('-', '')}`,
            };
          });
        }
      });
    }
    if (list[index].panes) {
      list[index].panes = list[index].panes.map((item) => {
        if (item.list.length) {
          item.list = item.list.map((it) => {
            return {
              ...it,
              id: v4().replaceAll('-', ''),
              element_code: `${it.element_control}_${v4().replaceAll('-', '')}`,
            };
          });
        }
      });
    }
    if (list[index].panel) {
      list[index].panel = list[index].panel.map((item) => {
        if (item.list.length) {
          item.list = item.list.map((it) => {
            return {
              ...it,
              id: v4().replaceAll('-', ''),
              element_code: `${it.element_control}_${v4().replaceAll('-', '')}`,
            };
          });
        }
      });
    }
    if (list[index].div_list) {
      list[index].div_list = list[index].div_list.map((item) => {
        if (item.list.length) {
          item.list = item.list.map((it) => {
            return {
              ...it,
              id: v4().replaceAll('-', ''),
              element_code: `${it.element_control}_${v4().replaceAll('-', '')}`,
            };
          });
        }
      });
    }
    if (list[index].list) {
      for (let i = 0; i < list[index].list.length; i++) {
        list[index].list[i].id = v4().replaceAll('-', '');
        list[index].list[i].element_code = `${
          list[index].list[i].element_control
        }_${v4().replaceAll('-', '')}`;
      }
    }
    // if (
    //   oldList[index].element_control === 'radio' ||
    //   oldList[index].element_control === 'checkbox' ||
    //   oldList[index].element_control === 'select'
    // ) {
    //   copyData = {
    //     ...copyData,
    //     options: {
    //       ...copyData.options,
    //       options: copyData.options.options.map((item: any) => ({ ...item })),
    //     },
    //   };
    // }
    // console.log(copyData, list);
  };
  const handleCopyClick = (index: number, list: any[], name: string) => {
    let oldList;
    const id = v4().replaceAll('-', '');
    oldList = JSON.parse(JSON.stringify(props.widgetForm[name]));
    let copyData = {
      ...list[index],
      id,
      element_code: `${list[index].element_control}_${id}`,
      rules: list[index].rules,
    };
    handleFunctionCopy(list, index);
    if (name == 'display_area') {
      emit('update:widgetForm', {
        ...props.widgetForm,
        display_area: handleListInsert(list[index].id, oldList, copyData),
      });
    } else if (name == 'hidden_area') {
      emit('update:widgetForm', {
        ...props.widgetForm,
        hidden_area: handleListInsert(list[index].id, oldList, copyData),
      });
    } else if (name == 'trash_area') {
      emit('update:widgetForm', {
        ...props.widgetForm,
        trash_area: handleListInsert(list[index].id, oldList, copyData),
      });
    } else if (name == 'button_area') {
      emit('update:widgetForm', {
        ...props.widgetForm,
        button_area: handleListInsert(list[index].id, oldList, copyData),
      });
    }
    updateWidgetFormSelectCore(copyData);
    // if (name == 'display_area') {
    //   const id = v4().replaceAll('-', '');
    //   oldList = JSON.parse(JSON.stringify(props.widgetForm.display_area));
    //   let copyData = {
    //     ...list[index],
    //     id,
    //     element_code: `${list[index].element_control}_${id}`,
    //     rules: list[index].rules ?? {},
    //   };
    //   handleFunctionCopy(list, index);
    //   emit('update:widgetForm', {
    //     ...props.widgetForm,
    //     display_area: handleListInsert(list[index].id, oldList, copyData),
    //   });
    //   updateWidgetFormSelectCore(copyData);
    // } else if (name == 'hidden_area') {
    //   const id = v4().replaceAll('-', '');
    //   oldList = JSON.parse(JSON.stringify(props.widgetForm.hidden_area));
    //   let copyData = {
    //     ...list[index],
    //     id,
    //     element_code: `${list[index].element_control}_${id}`,
    //     rules: list[index].rules ?? {},
    //   };
    //   handleFunctionCopy(list, index);
    //   emit('update:widgetForm', {
    //     ...props.widgetForm,
    //     hidden_area: handleListInsert(list[index].id, oldList, copyData),
    //   });
    //   updateWidgetFormSelectCore(copyData);
    // } else if (name == 'trash_area') {
    //   const id = v4().replaceAll('-', '');
    //   oldList = JSON.parse(JSON.stringify(props.widgetForm.trash_area));
    //   let copyData = {
    //     ...list[index],
    //     id,
    //     element_code: `${list[index].element_control}_${id}`,
    //     rules: list[index].rules ?? {},
    //   };
    //   handleFunctionCopy(list, index);
    //   emit('update:widgetForm', {
    //     ...props.widgetForm,
    //     trash_area: handleListInsert(list[index].id, oldList, copyData),
    //   });
    //   updateWidgetFormSelectCore(copyData);
    // } else if (name == 'button_area') {
    //   const id = v4().replaceAll('-', '');
    //   oldList = JSON.parse(JSON.stringify(props.widgetForm.button_area));
    //   let copyData = {
    //     ...list[index],
    //     id,
    //     element_code: `${list[index].element_control}_${id}`,
    //     rules: list[index].rules ?? {},
    //   };
    //   handleFunctionCopy(list, index);
    //   emit('update:widgetForm', {
    //     ...props.widgetForm,
    //     button_area: handleListInsert(list[index].id, oldList, copyData),
    //   });
    //   updateWidgetFormSelectCore(copyData);
    // }
  };
  const handleFunction = (list: any, index: number) => {
    if (list.length - 1 === index) {
      if (index === 0) {
        nextTick(() => updateWidgetFormSelectCore(null));
      } else {
        updateWidgetFormSelectCore(list[index - 1]);
      }
    } else {
      updateWidgetFormSelectCore(list[index + 1]);
    }
  };
  const handleDeleteClick = (index: number, list: any[], name: string) => {
    let oldList;
    oldList = JSON.parse(JSON.stringify(props.widgetForm[name]));
    handleFunction(list, index);
    if (name == 'display_area') {
      emit('update:widgetForm', {
        ...props.widgetForm,
        display_area: handleListDelete(list[index].id, oldList),
      });
    } else if (name == 'hidden_area') {
      emit('update:widgetForm', {
        ...props.widgetForm,
        hidden_area: handleListDelete(list[index].id, oldList),
      });
    } else if (name == 'trash_area') {
      emit('update:widgetForm', {
        ...props.widgetForm,
        trash_area: handleListDelete(list[index].id, oldList),
      });
    } else if (name == 'button_area') {
      emit('update:widgetForm', {
        ...props.widgetForm,
        button_area: handleListDelete(list[index].id, oldList),
      });
    }
    // if (name == 'display_area') {
    //   oldList = JSON.parse(JSON.stringify(props.widgetForm.display_area));
    //   handleFunction(list, index);
    //   emit('update:widgetForm', {
    //     ...props.widgetForm,
    //     display_area: handleListDelete(list[index].id, oldList),
    //   });
    // } else if (name == 'hidden_area') {
    //   oldList = JSON.parse(JSON.stringify(props.widgetForm.hidden_area));
    //   handleFunction(list, index);
    //   emit('update:widgetForm', {
    //     ...props.widgetForm,
    //     hidden_area: handleListDelete(list[index].id, oldList),
    //   });
    // } else if (name == 'trash_area') {
    //   oldList = JSON.parse(JSON.stringify(props.widgetForm.trash_area));
    //   handleFunction(list, index);
    //   emit('update:widgetForm', {
    //     ...props.widgetForm,
    //     trash_area: handleListDelete(list[index].id, oldList),
    //   });
    // } else if (name == 'button_area') {
    //   oldList = JSON.parse(JSON.stringify(props.widgetForm.button_area));
    //   handleFunction(list, index);
    //   emit('update:widgetForm', {
    //     ...props.widgetForm,
    //     button_area: handleListDelete(list[index].id, oldList),
    //   });
    // }
  };
  const handleFunctionMove = (list: any[], newIndex: number, name?: string) => {
    const id = v4().replaceAll('-', '');
    list[newIndex] = {
      ...list[newIndex],
      id,
      element_code: `${list[newIndex].element_code}`
        ? `${list[newIndex].element_code}`
        : `${list[newIndex].element_control}_${id}`,
    };

    if (
      list[newIndex].element_control === 'radio' ||
      list[newIndex].element_control === 'checkbox' ||
      list[newIndex].element_control === 'select'
    ) {
      list[newIndex] = {
        ...list[newIndex],
      };
    }
    if (list[newIndex].element_control === 'tabs') {
      list[newIndex] = {
        ...list[newIndex],
        panes: list[newIndex].panes.map((item: any) => {
          return {
            ...item,
            name: `${list[newIndex].element_control}_${v4().replaceAll('-', '')}`,
          };
        }),
      };
    }

    if (name == 'button_area' && ['button'].includes(list[newIndex].element_control)) {
      list[newIndex].width = '20%';
    }
    if (
      (name == 'display_area' || name == 'hidden_area' || name == 'trash_area') &&
      props.isTables
    ) {
      list[newIndex].width = '';
    }
  };

  const handleMoveAddStr = (event: any) => {
    if (props.isTables) {
      if (
        ['widget-form-display', 'widget-form-hidden', 'widget-form-trash'].includes(
          event.from.className,
        ) &&
        ['widget-col-list widget-button-list', 'widget-form-button'].includes(event.to.className) &&
        ['button'].includes(event.draggedContext.element.element_control)
      ) {
        event.draggedContext.element.isShowType = false;
      } else {
        event.draggedContext.element.isShowType = true;
      }
      if (
        ['widget-form-display', 'widget-form-hidden', 'widget-form-trash'].includes(
          event.from.className,
        ) &&
        ['widget-col-list widget-button-list', 'widget-form-button'].includes(event.to.className) &&
        !['button'].includes(event.draggedContext.element.element_control)
      ) {
        return false;
      }
      if (
        ['widget-col-list widget-foldedPanel-list'].includes(event.to.className) &&
        ['buttonArea'].includes(event.draggedContext.element.element_control)
      ) {
        return false;
      }
      if (
        ['widget-col-list widget-divLayout-list'].includes(event.to.className) &&
        ['divLayout'].includes(event.draggedContext.element.element_control)
      ) {
        return false;
      }
      if (
        [
          'widget-col-list widget-button-list',
          'widget-form-button',
          'widget-form-hidden',
          'widget-form-trash',
        ].includes(event.from.className) &&
        ['widget-form-display', 'widget-col-list widget-button-list'].includes(
          event.to.className,
        ) &&
        ['foldedPanel'].includes(event.draggedContext.element.element_control)
      ) {
        return false;
      }
    }
  };
  const handleMoveAdd = (event: any, name: string) => {
    const { newIndex, from } = event;
    let list;
    if (from.className == '') {
      if (name == 'display_area') {
        list = JSON.parse(JSON.stringify(props.widgetForm.display_area));
        handleFunctionMove(list, newIndex, name);
        emit('update:widgetForm', { ...props.widgetForm, display_area: list });
        updateWidgetFormSelectCore(list[newIndex]);
        // emit('update:widgetFormSelect', list[newIndex]);
      } else if (name == 'hidden_area') {
        list = JSON.parse(JSON.stringify(props.widgetForm.hidden_area));
        handleFunctionMove(list, newIndex, name);
        emit('update:widgetForm', { ...props.widgetForm, hidden_area: list });
        updateWidgetFormSelectCore(list[newIndex]);
      } else if (name == 'trash_area') {
        list = JSON.parse(JSON.stringify(props.widgetForm.trash_area));
        handleFunctionMove(list, newIndex, name);
        emit('update:widgetForm', { ...props.widgetForm, trash_area: list });
        updateWidgetFormSelectCore(list[newIndex]);
      } else if (name == 'button_area') {
        list = JSON.parse(JSON.stringify(props.widgetForm.button_area));
        handleFunctionMove(list, newIndex, name);
        emit('update:widgetForm', { ...props.widgetForm, button_area: list });
        updateWidgetFormSelectCore(list[newIndex]);
      }
    }
  };
</script>

<style lang="scss" scoped>
  .mike_group {
    float: left;
    padding: 1px 2px;
    position: relative;
    z-index: 999;
    .tabs_postionBottom {
      position: absolute;
      bottom: 0;
      right: 0;
      height: 28px;
      line-height: 28px;
      z-index: 999;
      // background: #409eff;
      background: var(--el-color-primary);
      width: 26px;
      display: flex;
      justify-content: center;
      align-items: center;
      svg {
        font-size: 14px;
        color: #fff;
        margin: 0 5px;
        cursor: pointer;
      }
    }
    .tabs_postionTop {
      position: absolute;
      top: 0;
      left: 0;
      height: 28px;
      line-height: 28px;
      z-index: 999;
      // background: #409eff;
      background: var(--el-color-primary);
      width: 26px;
      display: flex;
      justify-content: center;
      align-items: center;
      svg {
        font-size: 14px;
        color: #fff;
        margin: 0 5px;
        cursor: move;
      }
    }
  }
  .widget-col-list,
  .widget-col {
    box-sizing: border-box;
    height: 100%;
  }
  :deep(.el-tabs__nav-scroll) {
    padding-left: 0 !important;
  }
  :deep(.el-tabs__content) {
    padding: 10px 0;
    min-height: 50px;
  }
</style>
